package com.example.client_group5;

import java.net.URL;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.json.JSONArray;
import org.json.JSONObject;

import com.example.base.AppBaseActivity;

import util.DateUtil;
import util.HttpClientFactory;
import util.StringUtil;
import android.os.Bundle;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.Spannable;
import android.text.util.Linkify;
import android.util.Log;

import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

public class TweetDetail extends AppBaseActivity {
	private LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL);
	private ScrollView scroll;
	private LinearLayout l;
	private LinearLayout footer;
	private int top;
	private LinearLayout layout;
	private LinearLayout replyedLayout;
	private LinearLayout layoutItem;
	private LinearLayout profileLayout;
	private LinearLayout parentLayout;
	private TextView tweetTileText;
	private View tweetBt;
    private View replyButton;
    private View retweetButton;
    private View favoriteButton;
    //private View shareButton;
    private View deleteButton;
    private String[] info;
    private int count_retweets = 0;
    private int count_favorites = 0;
	private ImageManager manager;
	private ArrayList<ArrayList<Tweet>> tweets;
    private ArrayList<Tweet> replyedTweets;
    private ArrayList<Tweet> replyTweets;
    private UserManager userProfile;
    private ProgressBar progressBar;
    private DateUtil dateUtil;
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//				WindowManager.LayoutParams.FLAG_FULLSCREEN);
//		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        
        setContentView(R.layout.activity_tweet_detail);
        registerBaseActivityReceiver();
        userProfile = SignInActivity.userProfile;
        manager = ImageManager.getInstance(getApplicationContext());
        layout = (LinearLayout)findViewById(R.id.layout_list_id);
        
        
        ImageView avatar = (ImageView)findViewById(R.id.avatar_id);
        TextView fullnameText = (TextView)findViewById(R.id.fullname);
        TextView usernameText = (TextView)findViewById(R.id.username);
        TextView contentText = (TextView)findViewById(R.id.detail);
        TextView timeText = (TextView)findViewById(R.id.time_id);
        
        dateUtil = new DateUtil();
        
        Bundle b = getIntent().getExtras();
        info = b.getStringArray("tweet");
        
        fullnameText.setText(info[1]);
        usernameText.setText(info[2]);

        contentText.setText(info[3]);
        Linkify.addLinks(contentText, Linkify.WEB_URLS);
       
        Pattern userMatcher = Pattern.compile("\\B@[^:\\s]+");
        String userViewURL = "net.cogitas.findtweets.user://";
        Linkify.addLinks(contentText, userMatcher, userViewURL);
        
       
        
        if(contentText.getText() instanceof Spannable)
        	StringUtil.removeUnderlines((Spannable)contentText.getText());
        
//        timeText.setText(info[4]);
        timeText.setText(new DateUtil().fomatDate(info[4]));
        avatar.setTag(info[9]);
        
        progressBar = (ProgressBar)findViewById(R.id.progress_bar);
        manager.displayImage(info[9], TweetDetail.this, avatar, progressBar);
       
        tweetBt = (View)findViewById(R.id.btTweet);
        tweetBt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				Intent i = new Intent(TweetDetail.this, TweetActivity.class);
				Bundle b = new Bundle();
				String[] replyInfo = {"tweet"};
				b.putStringArray("reply", replyInfo);
				i.putExtras(b);
				startActivity(i);
				finish();
			}
		});
        
       
        tweetTileText = (TextView)findViewById(R.id.tweet_title);
        tweetTileText.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
				
			}
		});
        
        profileLayout = (LinearLayout) findViewById(R.id.profile_id);
        profileLayout.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(TweetDetail.this, ProfileActivity.class);
				Bundle b = new Bundle();
				// info[0]
				// user_id, fullname, username, image_url
				String[] infoProfile = {info[8], info[1], info[2], info[9]};
				b.putStringArray("user", infoProfile);
				i.putExtras(b);
				startActivity(i);
				finish();
			}
		});
        
        
        if(!info[10].equals("")){
        	ImageView imageView = (ImageView) findViewById(R.id.image_view_id);
        	imageView.setImageBitmap(getBitmap(info[10]));
        }
        Log.d("info7", "AAAAA: " + info[7]);
        if(!info[7].equals("")){
        	ImageView retweetNotice = (ImageView)findViewById(R.id.retweet_notice_id);
    	    retweetNotice.setBackgroundResource(R.drawable.retweet_notice);
    	        	
    	    TextView byUser = (TextView)findViewById(R.id.retweet_by_id);
    	    byUser.setText("Retweeted by " + info[7]);
        }
        replyButton = (View)findViewById(R.id.reply_id);

        replyButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				ArrayList<String> array = new ArrayList<String>();
				Pattern p = Pattern.compile("@(\\w|\\d|-|_){5,15}");
				Matcher result = p.matcher(info[3]);
				while(result.find()){
					array.add(result.group(0));
				}
				String[] replyInfo = new String[3 + array.size()];
				replyInfo[0] = info[0];
				replyInfo[1] = info[2];
				replyInfo[2] = "";
				for(int i = 3; i < array.size() + 3; i ++){
					replyInfo[i] = array.get(i - 3);
				}
				Intent i = new Intent(TweetDetail.this, TweetActivity.class);
				Bundle b = new Bundle();
				b.putStringArray("reply", replyInfo);
				i.putExtras(b);
				startActivity(i);
				finish();
			}
		});
        
        
        LinearLayout layoutDelete = (LinearLayout)findViewById(R.id.layout_delete_id);
        deleteButton = (View)findViewById(R.id.delete_id);
        retweetButton = (View)findViewById(R.id.retweet_id);
        if(info[2].equals(userProfile.getUserName("username", ""))){
        	layoutDelete.setVisibility(View.VISIBLE);
        	retweetButton.setBackgroundResource(R.drawable.retweet_disable);
        	retweetButton.setEnabled(false);
        }
        else{
	        if(info[5].equals("true")){
	        	retweetButton.setBackgroundResource(R.drawable.retweet_bt2);

	        }
        }
        retweetButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				final String tweet_id = info[0];
				if(info[5].equals("false")){
					AlertDialog alertDialog = new AlertDialog.Builder(TweetDetail.this).create();
					alertDialog.setTitle("Retweet");
					alertDialog.setMessage("Retweet this to your followers?");
					alertDialog.setCancelable(false);
					alertDialog.setButton("Retweet", new DialogInterface.OnClickListener(){	    	
						public void onClick(DialogInterface dialog, int id) {
							createRetweet(tweet_id);
							if(info.length ==  12){
								int position = Integer.parseInt(info[info.length - 1]);
								Tweet tweet = LazyLoading.adapter.getItem(position);
								tweet.isRetweeted = true;
								LazyLoading.adapter.notifyDataSetChanged();
							}
							if(info.length == 13){
								int position = Integer.parseInt(info[info.length - 1]);
								Tweet tweet = ViewTweetUserActivity.adapter.getItem(position);
								tweet.isRetweeted = true;
								ViewTweetUserActivity.adapter.notifyDataSetChanged();
								
								// Check for update home timeline
								position = getPosition(tweet);
								if(position != -1){
									tweet = LazyLoading.adapter.getItem(position);
									tweet.isRetweeted = true;
									LazyLoading.adapter.notifyDataSetChanged();
									
								}
							}
							if(info.length == 14){
								int position = Integer.parseInt(info[info.length - 1]);
								Tweet tweet = FavoriteTweet.adapter.getItem(position);
								tweet.isRetweeted = true;
								FavoriteTweet.adapter.notifyDataSetChanged();
								
								// Check for update home timeline
								position = getPosition(tweet);
								if(position != -1){
									tweet = LazyLoading.adapter.getItem(position);
									tweet.isRetweeted = true;
									LazyLoading.adapter.notifyDataSetChanged();
									
								}
							}
							finish();
							return;
						}
					}); 
					alertDialog.setButton3("Quote", new DialogInterface.OnClickListener() {			
						@Override
						public void onClick(DialogInterface dialog, int id) {
							Intent i = new Intent(TweetDetail.this, TweetActivity.class);
							Bundle b = new Bundle();
							// quote
							String[] value = {info[2], info[3]}; 
							b.putStringArray("reply", value);
							i.putExtras(b);
							startActivity(i);
							finish();
							return;
						}
					});
					alertDialog.setButton2("Cancle", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							dialog.cancel();
						}
					});
					alertDialog.show();
					
				}
				else{
					AlertDialog alertDialog = new AlertDialog.Builder(TweetDetail.this).create();
					alertDialog.setTitle("Retweet");
					alertDialog.setMessage("Undo this retweet?");
					alertDialog.setCancelable(false);
					alertDialog.setButton("Undo", new DialogInterface.OnClickListener(){	    	
						public void onClick(DialogInterface dialog, int id) {
							deleteRetweet(tweet_id);
							if(info.length == 12){
								int position = Integer.parseInt(info[info.length - 1]);
								Tweet tweet = LazyLoading.adapter.getItem(position);
								tweet.isRetweeted = false;
								LazyLoading.adapter.notifyDataSetChanged();
							}
							if(info.length == 13){
								int position = Integer.parseInt(info[info.length - 1]);
								Tweet tweet = ViewTweetUserActivity.adapter.getItem(position);
								tweet.isRetweeted = false;
								ViewTweetUserActivity.adapter.notifyDataSetChanged();
								
								// Check for update home timeline
								position = getPosition(tweet);
								if(position != -1){
									tweet = LazyLoading.adapter.getItem(position);
									tweet.isRetweeted = false;
									LazyLoading.adapter.notifyDataSetChanged();
									
								}
							}
							if(info.length == 14){
								int position = Integer.parseInt(info[info.length - 1]);
								Tweet tweet = FavoriteTweet.adapter.getItem(position);
								tweet.isRetweeted = false;
								FavoriteTweet.adapter.notifyDataSetChanged();
								
								// Check for update home timeline
								position = getPosition(tweet);
								if(position != -1){
									tweet = LazyLoading.adapter.getItem(position);
									tweet.isRetweeted = false;
									LazyLoading.adapter.notifyDataSetChanged();
									
								}
							}
							finish();
							return;
						}
					}); 
					alertDialog.setButton3("Quote", new DialogInterface.OnClickListener() {			
						@Override
						public void onClick(DialogInterface dialog, int id) {
							Intent i = new Intent(TweetDetail.this, TweetActivity.class);
							Bundle b = new Bundle();
							// quote
							String[] value = {info[2], info[3]};
							b.putStringArray("reply", value);
							i.putExtras(b);
							startActivity(i);
							finish();
							return;
						}
					});
					alertDialog.setButton2("Cancle", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							dialog.cancel();
						}
					});
					alertDialog.show();
					
				}
			
			}
		});
        deleteButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				AlertDialog alertDialog = new AlertDialog.Builder(TweetDetail.this).create();
				alertDialog.setTitle("Delete");
				alertDialog.setMessage("Do you want to delete this Tweet");
				alertDialog.setCancelable(false);
				alertDialog.setButton("Yes", new DialogInterface.OnClickListener(){	    	
					public void onClick(DialogInterface dialog, int id) {
						deleteTweet(info[0]);
						if(info.length == 12){
							int position = Integer.parseInt(info[info.length - 1]);
							Tweet tweet = LazyLoading.adapter.getItem(position);
							LazyLoading.adapter.remove(tweet);
							LazyLoading.adapter.notifyDataSetChanged();
						}
						if(info.length == 13){
							int position = Integer.parseInt(info[info.length - 1]);
							Tweet tweet = ViewTweetUserActivity.adapter.getItem(position);
							
							ViewTweetUserActivity.adapter.remove(tweet);
							ViewTweetUserActivity.adapter.notifyDataSetChanged();
							
							// Check for update home timeline
							position = getPosition(tweet);
							if(position != -1){
								tweet = LazyLoading.adapter.getItem(position);
								LazyLoading.adapter.remove(tweet);
								LazyLoading.adapter.notifyDataSetChanged();
								
							}
						}
						if(info.length == 14){
							int position = Integer.parseInt(info[info.length - 1]);
							Tweet tweet = FavoriteTweet.adapter.getItem(position);
							
							FavoriteTweet.adapter.remove(tweet);
							FavoriteTweet.adapter.notifyDataSetChanged();
							// Check for update home timeline
							position = getPosition(tweet);
							if(position != -1){
								tweet = LazyLoading.adapter.getItem(position);
								LazyLoading.adapter.remove(tweet);
								LazyLoading.adapter.notifyDataSetChanged();
								
							}
						}
						finish();
						return;
					}
				}); 
				alertDialog.setButton2("No", new DialogInterface.OnClickListener() {			
					@Override
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();				
					}
				});
				alertDialog.show();
			}
		});
        
        favoriteButton = (View)findViewById(R.id.favorite_id);
        if(info[6].equals("true")){
        	favoriteButton.setBackgroundResource(R.drawable.favorite_icon2);
        }
        favoriteButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				String tweet_id = info[0];
				if(info[6].equals("false")){
					info[6] = "true";
					createFavorite(tweet_id);
					if(info.length == 12){
						int position = Integer.parseInt(info[info.length - 1]);
						Tweet tweet = LazyLoading.adapter.getItem(position);
						tweet.isFavorite = true;
						LazyLoading.adapter.notifyDataSetChanged();
					}
					if(info.length == 13){
						int position = Integer.parseInt(info[info.length - 1]);
						Tweet tweet = ViewTweetUserActivity.adapter.getItem(position);
						tweet.isFavorite = true;
						ViewTweetUserActivity.adapter.notifyDataSetChanged();
						// Check for update home timeline
						position = getPosition(tweet);
						if(position != -1){
							tweet = LazyLoading.adapter.getItem(position);
							tweet.isFavorite = true;
							LazyLoading.adapter.notifyDataSetChanged();
						}
						
					}
					if(info.length == 14){
						int position = Integer.parseInt(info[info.length - 1]);
						Tweet tweet = FavoriteTweet.adapter.getItem(position);
						tweet.isFavorite = true;
						FavoriteTweet.adapter.notifyDataSetChanged();
						// Check for update home timeline
						position = getPosition(tweet);
						if(position != -1){
							tweet = LazyLoading.adapter.getItem(position);
							tweet.isFavorite = true;
							LazyLoading.adapter.notifyDataSetChanged();
						}
					}
					favoriteButton.setBackgroundResource(R.drawable.favorite_icon2);
				}
				else{
					favoriteButton.setBackgroundResource(R.drawable.favorite_icon);
					info[6] = "false";
					deleteFavorite(tweet_id);
					if(info.length == 12){
						int position = Integer.parseInt(info[info.length - 1]);
						Tweet tweet = LazyLoading.adapter.getItem(position);
						tweet.isFavorite = false;
						LazyLoading.adapter.notifyDataSetChanged();
					}
					if(info.length == 13){
						int position = Integer.parseInt(info[info.length - 1]);
						Tweet tweet = ViewTweetUserActivity.adapter.getItem(position);
						tweet.isFavorite = false;
						ViewTweetUserActivity.adapter.notifyDataSetChanged();
						
						// Check for update home timeline
						position = getPosition(tweet);
						if(position != -1){
							tweet = LazyLoading.adapter.getItem(position);
							tweet.isFavorite = false;
							LazyLoading.adapter.notifyDataSetChanged();
							
						}
					}
					if(info.length == 14){
						int position = Integer.parseInt(info[info.length - 1]);
						Tweet tweet = FavoriteTweet.adapter.getItem(position);
						tweet.isFavorite = false;
						FavoriteTweet.adapter.notifyDataSetChanged();
						
						// Check for update home timeline
						position = getPosition(tweet);
						if(position != -1){
							tweet = LazyLoading.adapter.getItem(position);
							tweet.isFavorite = false;
							LazyLoading.adapter.notifyDataSetChanged();
							
						}
					}
				}
			}
		});
        
        // focus view on scroll view
        scroll = (ScrollView)findViewById(R.id.scroll_id);
        l = (LinearLayout)findViewById(R.id.layout_profile_id);
        footer = (LinearLayout)findViewById(R.id.footer);	
        parentLayout = (LinearLayout)findViewById(R.id.parent_layout_id);
        
        replyedLayout = (LinearLayout)findViewById(R.id.replyed_layout_id);
        layoutItem = (LinearLayout)findViewById(R.id.layout_list_item_id);
       
        tweets = getTweets(info[0], 5, 0, 0);
        
        replyedTweets = tweets.get(0);
        replyTweets = tweets.get(1);
        
        if(replyedTweets.size() == 0)
        {
        	parentLayout.setVisibility(View.GONE);
        	footer.setVisibility(View.GONE);
        }
        else{
        	TextView replyedText = (TextView)findViewById(R.id.text_replyed_id);
        	replyedText.setText("In reply to " + info[1]);
        	 for(int i = 0; i < replyedTweets.size(); i ++){
 	        	LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 				View v = vi.inflate(R.layout.listitem, null);
 				final Tweet tweet = replyedTweets.get(i);
 				if (tweet != null) {
 					TextView fullname = (TextView)v.findViewById(R.id.fullname);
 					TextView username = (TextView) v.findViewById(R.id.username);
 					TextView mention = (TextView)v.findViewById(R.id.mention);
 					TextView message = (TextView) v.findViewById(R.id.content);
 					ImageView image = (ImageView) v.findViewById(R.id.avatar);
 					TextView time = (TextView)v.findViewById(R.id.time_id);
 					progressBar = (ProgressBar)v.findViewById(R.id.progress_bar);
 					if(fullname != null){
 						fullname.setText(tweet.fullname);
 					}
 					if (username != null) {
 						username.setText(tweet.username);
 					}
 					if(mention != null){
 						mention.setText(tweet.mention);
 					}
 	
 					if(message != null) {
 						message.setText(tweet.content);
 					}
 					
 					if(image != null) {
 						image.setTag(tweet.image_url);
 						manager.displayImage(tweet.image_url, TweetDetail.this, image, progressBar);
 					}
 					if(time != null){
 						dateUtil.getDiffDate(tweet.time);
 						if(dateUtil.getYear() != 0){
 							time.setText(dateUtil.getYear() + "y");
 						}
 						else if(dateUtil.getMonth() != 0){
 							time.setText(dateUtil.getYear() + "M");
 						}
 						else if(dateUtil.getDay() != 0){
 							time.setText(dateUtil.getDay() + "d");
 						}
 						else if(dateUtil.getHour() != 0){
 							time.setText(dateUtil.getHour() + "h");
 						}
 						else if(dateUtil.getMinute() != 0){
 							time.setText(dateUtil.getMinute() + "m");
 						}
 						else if(dateUtil.getSecond() != 0){
 							time.setText(dateUtil.getSecond() + "s");
 						}
 						dateUtil.resetTime();
 					}
 				}
 				v.setOnClickListener(new OnClickListener() {
 					@Override
 					public void onClick(View arg0) {
 						// TODO Auto-generated method stub
 						Log.d("tag", tweet.content);
 						Bundle b = new Bundle();
						String[] info = {tweet.tweet_id, tweet.fullname, tweet.username, tweet.content, tweet.time, "" + tweet.isRetweeted, "" + tweet.isFavorite,
										tweet.retweetedUser, tweet.user_id, tweet.image_url, tweet.img_up_url};
						b.putStringArray("tweet", info);
						Intent i = getIntent();
						i.putExtras(b);
						startActivity(i);
						finish();
 					}
 				});
 				replyedLayout.addView(v);
 	        }
        }
        if(replyTweets.size() == 0){
        	layout.setVisibility(View.GONE);
        }
        else{
	        for(int i = 0; i < replyTweets.size(); i ++){
	        	LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				View v = vi.inflate(R.layout.listitem, null);
				final Tweet tweet = replyTweets.get(i);
				if (tweet != null) {
					TextView fullname = (TextView)v.findViewById(R.id.fullname);
					TextView username = (TextView) v.findViewById(R.id.username);
					TextView mention = (TextView)v.findViewById(R.id.mention);
					TextView message = (TextView) v.findViewById(R.id.content);
					ImageView image = (ImageView) v.findViewById(R.id.avatar);
					TextView time = (TextView)v.findViewById(R.id.time_id);
					progressBar = (ProgressBar)v.findViewById(R.id.progress_bar);
					if(fullname != null){
						fullname.setText(tweet.fullname);
					}
					if (username != null) {
						username.setText(tweet.username);
					}
					if(mention != null){
						mention.setText(tweet.mention);
					}
	
					if(message != null) {
						message.setText(tweet.content);
					}
					if(image != null) {
						image.setTag(tweet.image_url);
 						manager.displayImage(tweet.image_url, TweetDetail.this, image, progressBar);
					}
					if(time != null){
 						dateUtil.getDiffDate(tweet.time);
 						if(dateUtil.getYear() != 0){
 							time.setText(dateUtil.getYear() + "y");
 						}
 						else if(dateUtil.getMonth() != 0){
 							time.setText(dateUtil.getYear() + "M");
 						}
 						else if(dateUtil.getDay() != 0){
 							time.setText(dateUtil.getDay() + "d");
 						}
 						else if(dateUtil.getHour() != 0){
 							time.setText(dateUtil.getHour() + "h");
 						}
 						else if(dateUtil.getMinute() != 0){
 							time.setText(dateUtil.getMinute() + "m");
 						}
 						else if(dateUtil.getSecond() != 0){
 							time.setText(dateUtil.getSecond() + "s");
 						}
 						dateUtil.resetTime();
 					}
				}
				v.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						Log.d("tag", tweet.content);
						Bundle b = new Bundle();
						String[] info = {tweet.tweet_id, tweet.fullname, tweet.username, tweet.content, tweet.time, "" + tweet.isRetweeted, "" + tweet.isFavorite,
										tweet.retweetedUser, tweet.user_id, tweet.image_url, tweet.img_up_url};
						b.putStringArray("tweet", info);
						Intent i = getIntent();
						i.putExtras(b);
						startActivity(i);
//						finish();
					}
				});
				
				layoutItem.addView(v);
	        }
        }
        if(count_retweets == 0){
        	RelativeLayout layoutRetweets = (RelativeLayout)findViewById(R.id.retweets_layout_id);
        	layoutRetweets.setVisibility(View.GONE);
        }
        else{
        	TextView countRetweetText = (TextView)findViewById(R.id.retweets_count_id);
        	countRetweetText.setText("" + count_retweets);
        	//String tweet_id=info[0];
        	RelativeLayout retweet=(RelativeLayout)findViewById(R.id.retweets_layout_id);
        	retweet.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent i = new Intent(TweetDetail.this, RetweetActivity.class);
					Bundle bundle = new Bundle();
					//bundle.putString("tweet_id", tweet_id);
					bundle.putStringArray("tweet", info);
					i.putExtras(bundle);
					startActivity(i);
//					finish();
				}
			});
        }
        if(count_favorites == 0){
        	LinearLayout lineLayout = (LinearLayout)findViewById(R.id.line_id);
        	lineLayout.setVisibility(View.GONE);
        	RelativeLayout layoutRetweets = (RelativeLayout)findViewById(R.id.favorites_layout_id);
        	layoutRetweets.setVisibility(View.GONE);
        }
        else{
        	RelativeLayout favorite = (RelativeLayout)findViewById(R.id.favorites_layout_id);
        	TextView countFavoritesText = (TextView)findViewById(R.id.favorites_count_id);
        	countFavoritesText.setText(""+count_favorites);
        	favorite.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					
		        	Intent i = new Intent(TweetDetail.this, FavoriteByActivity.class);
					Bundle bundle = new Bundle();
					//bundle.putString("tweet_id", tweet_id);
					bundle.putStringArray("tweet", info);
					i.putExtras(bundle);
					startActivity(i);
//					finish();
				}
			});
        }
//          LoadData task = new LoadData();
//          task.execute();
    }
    public ArrayList<ArrayList<Tweet>> getTweets(String owner_id, int count, int since_id, int max_id){
		
		String getUrl = Setting.ipServer + "api/tweet/show-reply?tweet_id=" + owner_id;
		Log.d("tag", getUrl);
		ArrayList<Tweet> replyedTweets = new ArrayList<Tweet>();
		ArrayList<ArrayList<Tweet>> tweets = new ArrayList<ArrayList<Tweet>>();
		ArrayList<Tweet> replyTweets = new ArrayList<Tweet>();

		HttpClient client = HttpClientFactory.getThreadSafeClient();

		HttpGet get = new HttpGet(getUrl);
		 
		ResponseHandler<String> responseHandler = 
		        new BasicResponseHandler();

		String responseBody = null;
		try {
//		    responseBody = SignInActivity.client.execute(get, responseHandler);
			responseBody = client.execute(get, responseHandler);
		} catch(Exception ex) {
			  ex.printStackTrace();
		}
		Log.d("tag", "Tra ve: " + responseBody);
		JSONObject jsonObject = null;
		try{
			jsonObject = new JSONObject(responseBody);
			count_retweets = jsonObject.getInt("number_of_retweets");
			count_favorites = jsonObject.getInt("number_of_favorites");
			
			JSONArray jsonArray = jsonObject.getJSONArray("reply_tweet");
			for(int i = 0; i < jsonArray.length(); i ++){
				JSONObject t = jsonArray.getJSONObject(i);
				String tweet_id = t.get("id").toString();
				String mention = t.get("mentions").toString();
				String time = t.get("created_time").toString();
				String img_url = t.getString("img_url").toString();
				String content = t.get("content").toString().trim() + "\n" + img_url;
				boolean isRetweeted = t.getBoolean("is_retweeted");
				boolean isFavorite = t.getBoolean("is_favorite");
				String retweetedUser = t.getString("retweeted_user");
				
				JSONObject author = t.getJSONObject("author");
				
				String user_id = author.get("user_id").toString();
				String username = author.get("username").toString();
				
				String fullname = author.get("fullname").toString();
				String profile_url = author.get("avatar").toString();
				//Log.d("isReweet", "isRetweeted: "+isRetweeted);
				Tweet tweet = new Tweet(tweet_id, fullname, username, user_id, mention, content, img_url, profile_url, time, isRetweeted, isFavorite, retweetedUser);
				replyTweets.add(tweet);
				
			}
			jsonArray = jsonObject.getJSONArray("replyed_tweet");
			for(int i = 0; i < jsonArray.length(); i ++){
				JSONObject t = jsonArray.getJSONObject(i);
				String tweet_id = t.get("id").toString();
				String mention = t.get("mentions").toString();
				String time = t.get("created_time").toString();
				String img_url = t.getString("img_url").toString();
				String content = t.get("content").toString().trim() + "\n" + img_url;
				boolean isRetweeted = t.getBoolean("is_retweeted");
				boolean isFavorite = t.getBoolean("is_favorite");
				String retweetedUser = t.getString("retweeted_user");
				
				JSONObject author = t.getJSONObject("author");
				
				String user_id = author.get("user_id").toString();
				String username = author.get("username").toString();
				
				String fullname = author.get("fullname").toString();
				String profile_url = author.get("avatar").toString();
				//Log.d("isReweet", "isRetweeted: "+isRetweeted);
				Tweet tweet = new Tweet(tweet_id, fullname, username, user_id, mention, content, img_url, profile_url, time, isRetweeted, isFavorite, retweetedUser);
				replyedTweets.add(tweet);
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
		tweets.add(replyedTweets);
		tweets.add(replyTweets);
		
		return tweets;
    }
	public void createRetweet(String tweet_id){
		String url = Setting.ipServer + "api/tweet/retweet?tweet_id=" + tweet_id;
		HttpGet get = new HttpGet(url);
		 
		ResponseHandler<String> responseHandler = new BasicResponseHandler();

		String responseBody = null;
		try {
		    responseBody = HttpClientFactory.getThreadSafeClient().execute(get, responseHandler);
		    
		} catch(Exception ex) {
			  ex.printStackTrace();
		}
		Log.d("tag", "Create retweet: " + responseBody);
	}
	
	public void deleteRetweet(String tweet_id){
		String url = Setting.ipServer + "api/tweet/un-retweet?tweet_id=" + tweet_id;
		HttpGet get = new HttpGet(url);
		ResponseHandler<String> responseHandler = 
		        new BasicResponseHandler();

		String responseBody = null;
		try {
		    responseBody = HttpClientFactory.getThreadSafeClient().execute(get, responseHandler);
		    
		} catch(Exception ex) {
			  ex.printStackTrace();
		}
		Log.d("tag", "Delete retweet: " + responseBody);
		
	}
	
	public void createFavorite(String tweet_id){
		String url = Setting.ipServer + "api/tweet/create-favorite?tweet_id=" + tweet_id;
		HttpGet get = new HttpGet(url);
		 
		ResponseHandler<String> responseHandler = 
		        new BasicResponseHandler();

		String responseBody = null;
		try {
		    responseBody = HttpClientFactory.getThreadSafeClient().execute(get, responseHandler);
		    
		} catch(Exception ex) {
			  ex.printStackTrace();
		}
		Log.d("tag", "Tra ve: " + responseBody);
	}
	
	public void deleteFavorite(String tweet_id){
		String url = Setting.ipServer + "/api/tweet/un-favorite?tweet_id=" + tweet_id;
		HttpGet get = new HttpGet(url);
		ResponseHandler<String> responseHandler = 
		        new BasicResponseHandler();

		String responseBody = null;
		try {
		    responseBody = HttpClientFactory.getThreadSafeClient().execute(get, responseHandler);
		    
		} catch(Exception ex) {
			  ex.printStackTrace();
		}
		Log.d("tag", "Tra ve: " + responseBody);
	}
	public void deleteTweet(String tweet_id){
		String url = Setting.ipServer + "api/tweet/del-tweet?tweet_id=" + tweet_id;
		HttpGet get = new HttpGet(url);
		ResponseHandler<String> responseHandler = 
		        new BasicResponseHandler();

		String responseBody = null;
		try {
		    responseBody = HttpClientFactory.getThreadSafeClient().execute(get, responseHandler);
		    
		} catch(Exception ex) {
			  ex.printStackTrace();
		}
		Log.d("tag", "Tra ve: " + responseBody);
	}
	 public Bitmap getBitmap(String bitmapUrl) {
		try {
			URL url = new URL(bitmapUrl);
		    return BitmapFactory.decodeStream(url.openConnection().getInputStream()); 
		}
		catch(Exception ex) {return null;}
	}
	@Override
    public void onWindowFocusChanged (boolean hasFocus) {
        // the height will be set at this point
        top = l.getTop(); 
        Log.d("tag", "Top top top top top top top: " + top);
        params.height = top;
	    if(top > 100 && top < 360){
	    	if(replyTweets.size() == 0){
	    		params.height = 360;
	    	}
	    }
	    footer.setLayoutParams(params);
        scroll.post(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Log.d("top", "AAAAAAAAAAAA: " + top);
				if(top > 50){
					scroll.scrollTo(0, top - 50);
				}
			}
		});
    } 
	
	/*
	 * Get position of tweet in home timeline
	 * if exits return position
	 * else none exist return -1
	 * */
	public int getPosition(Tweet tweet){
		String id = tweet.tweet_id;
		int count = LazyLoading.adapter.getCount();
		for(int position = 0; position < count; position ++){
			Tweet element = LazyLoading.adapter.getItem(position);
			if(element.tweet_id.equals(id)){
				return position;
			}
		}
		return -1;
	}
	public boolean onKeyDown(int keycode, KeyEvent event){
		if(keycode == KeyEvent.KEYCODE_BACK){
			finish();
		}
    	return false;
	}
	public void onDestroy(){
		super.onDestroy();
		unRegisterBaseActivityReceiver();
	}
}
